/*  
/*  
=========================================================
  Options:
  There are some optional settings. The format for these are:
  veh = [this, n_civs ,[[name,action],[name,action]], Delay, Deserted timer, Respawns, Effect, Static] execVM "bus.sqf"

  
  Default respawn delay is 30 seconds, to set a custom
  respawn delay time, put that in the init as well. 
  Like this:
  veh = [this, 1,[[name,action],[name,action]], 15] execVM "bus.sqf"

  Default respawn time when vehicle is deserted, but not
  destroyed is 120 seconds. To set a custom timer for this 
  first put the respawn delay, then the deserted vehicle timer. (0 = disabled)
  Like this:  
  veh = [this, 1,[[name,action],[name,action]], 15, 10] execVM "bus.sqf"

  By default the number of respawns is infinite. To set a limit
  First set the other values then the number of respawns you want (0 = infinite).
  Like this:
  veh = [this, 1,[[name,action],[name,action]], 15, 10, 5] execVM "bus.sqf"


  Set this value to TRUE to add a special explosion effect to the wreck when respawning.
  Default value is FALSE, which will simply have the wreck disappear.
  Like this:
  veh = [this, 1,[[name,action],[name,action]], 15, 10, 5, TRUE] execVM "bus.sqf"
  
  By default the vehicle will respawn to the point where it first
  was when the mission started (static). This can be changed to 
  dynamic. Then the vehicle will respawn to the position where it was destroyed. 
  First set all the other values then set TRUE for dynamic or FALSE for static.
  Like this:
  veh = [this, 1,[[name,action],[name,action]],  15, 10, 5, TRUE, TRUE] execVM "bus.sqf"
  
  If you you want to set the INIT field of the respawned vehicle, first set all other 
  values, then set init commands. Those must be inside quotations.
  Like this:
  veh = [this, 1,[[name,action],[name,action]], 15, 10, 5, TRUE, FALSE, "this setDammage 0.5"] execVM "bus.sqf"
  
  Default values of all settings are:
  veh = [this, 1, [[name,action],[name,action]], 30, 120, 0, FALSE, FALSE] execVM "bus.sqf"
  
=========================================================
*/
 
if (!isServer) exitWith {};

_civilians = ["ibr_africaman1","ibr_africaman2","ibr_africaman3","ibr_africaman4","ibr_africaman5","ibr_africaman6","ibr_africaman7"];

// Define variables
_unit = _this select 0;
_civ_count = if (count _this > 1) then {_this select 1} else {7};
_locs = if (count _this > 2) then {_this select 2} else {[]};
_delay = if (count _this > 3) then {_this select 3} else {30};
_deserted = if (count _this > 4) then {_this select 4} else {120};
_respawns = if (count _this > 5) then {_this select 5} else {0};
_explode = if (count _this > 6) then {_this select 6} else {false};
_dynamic = if (count _this > 7) then {_this select 7} else {false};
_unitinit = if (count _this > 8) then {_this select 8} else {};
_haveinit = if (count _this > 9) then {true} else {false};
_next_idx = 0;
_target_done = true;

_firsttime = true;
_hasname = false;
_unitname = vehicleVarName _unit;
if (isNil _unitname) then {_hasname = false;} else {_hasname = true;};
_noend = true;
_run = true;
_rounds = 0;

if (_delay < 0) then {_delay = 0};
if (_deserted < 0) then {_deserted = 0};
if (_respawns <= 0) then {_respawns= 0; _noend = true;};
if (_respawns > 0) then {_noend = false};

_dir = getDir _unit;
_position = getPosASL _unit;
_type = typeOf _unit;
_dead = true;
_nodelay = true;
_mygroup = createGroup civilian;
_next_pos = position _unit;
_cur_idx= -1;
_cc = 0;
_wcount=0;
// Start monitoring the vehicle
while {_run} do 
{	
	if (!(_firsttime)) then { sleep (2 + random 10);};
    if ((getDammage _unit > 0.8) and ({alive _x} count crew _unit == 0)) then {_dead = true};

	// Check if the vehicle is deserted.
	if (_deserted > 0) then
	{
		if ((getPosASL _unit distance _position > 10) and ({alive _x} count crew _unit == 0) and (getDammage _unit < 0.8)) then 
		{
			_timeout = time + _deserted;
			sleep 0.1;
		 	waitUntil {_target_done or (_unit distance _next_pos < 50)  or (_timeout < time or !alive _unit or {alive _x} count crew _unit > 0)};
			if ({alive _x} count crew _unit > 0) then {_dead = false}; 
			if ({alive _x} count crew _unit == 0) then {_dead = true; _nodelay =true}; 
			if !(alive _unit) then {_dead = true; _nodelay = false}; 
		};
	};

	// Respawn vehicle
    if (_dead or _firsttime) then 
	{	
		if (_nodelay or _firsttime) then {sleep 0.1; _nodelay = false;} else {sleep _delay;};
		if (_dynamic) then {_position = getPosASL _unit; _dir = getDir _unit;};
		if (_explode) then {_effect = "M_TOW_AT" createVehicle getPosASL _unit; _effect setPosASL getPosASL _unit;};
		sleep 0.1;
		_firsttime =false;
		{ deleteVehicle _x } forEach (crew _unit); deleteVehicle _unit;
		//deleteVehicle _unit;
		//sleep 2;

		_unit = _type createVehicle _position;
		_target_done = true;
		_unit setPosASL _position;
		_unit setDir _dir;

		if (_haveinit) then 
					{_unit setVehicleInit format ["%1;", _unitinit];
					processInitCommands;};
		if (_hasname) then 
					{_unit setVehicleInit format ["%1 = this; this setVehicleVarName ""%1""",_unitname];
					processInitCommands;};

		[_unit] join _mygroup ;
		for "_x" from 1 to _civ_count  do {
			_civ = _civilians select (random (count _civilians - 1));
			_someciv = _mygroup createUnit [_civ, position _unit, [], 5, "NONE"];
			[_someciv] join _mygroup ;
			if (_x == 1) then {
				// _mygroup selectLeader _someciv;
				_someciv  assignAsDriver _unit; 
			} else {
				_someciv assignAsCargo _unit;
			};
			[_someciv] orderGetIn true;
		};
		
		_dead = false;
		// _pos = [_position, 20] call XfGetRanPointCircle
		// Check respawn amount
		if !(_noend) then {_rounds = _rounds + 1};
		if ((_rounds == _respawns) and !(_noend)) then {_run = false;};
	};
		//_target_done = true;

		
		if (!_dead and _next_idx < count _locs and ((_unit distance _next_pos < 15) or _target_done)) then {
			_target_done = false;
			_next_loc = _locs select (_next_idx);
			_next_action = _next_loc select 1;
			switch (true) do {
				case (_next_action == "MOVE" or _next_action == "MOVE_SLOW"): { 
					//_unit setVariable ["_on_Target",false,true];
					_next_pos = _next_loc select 0;
					if (_wcount>0) then {deleteWaypoint [_mygroup, 1];};
					_wp = _mygroup addWaypoint [position _next_pos, 5];
					[_mygroup,1] setWaypointType "MOVE";
					[_mygroup,1] setWaypointTimeout [60, 60, 60];
					_wcount=_wcount +1;
					switch (true) do {
						case (_next_action=="MOVE"): { 
							[_mygroup, 1] setWaypointSpeed "FULL";
						};
						case (_next_action=="MOVE_SLOW"): { 
						};
					};
					[_mygroup,1] setWaypointStatements ["true", "_target_done = true;"];
					_cur_idx = _next_idx;
					_next_idx = _next_idx + 1; 
				};
				case (_next_action=="CYCLE"): { 
					_next_wp = (_next_loc select 2) - 1;
					if (_next_wp < count _locs) then { _next_idx = _next_wp;};
					_target_done = true;
				};
			};
			//hintsilent format["New Bus %1 -> %2",_next_pos,_next_action];
			//sleep 20;

			//if (_next_idx == count _locs) then { _next_idx = 0;}
		};
		_cc=_cc+1;
		//hintsilent format["%7 == %1 -> %2 -> %3 -> %4 -> %5 -> %6 ",_dead ,_cur_idx + 1,_next_idx + 1,count _locs, _unit distance _next_pos, _target_done ,_cc];
};